package org.ihelpuoo.util;

import org.ihelpuoo.lang.LoaderException;
import org.ihelpuoo.lang.StringUtils;

public class IntegerRange
{
	private boolean	minInclusive;
	private boolean	maxInclusive;
	private int		min	= -1;
	private int		max	= -1;
	private boolean	isAlwaysTrue;

	public IntegerRange(String setting) throws LoaderException
	{
		setting = StringUtils.trim(setting);
		if (null == setting || setting.length() < 5)
			throw new LoaderException("Checker setting should not less than 5 char!");
		if ("[0,N)".equals(setting))
			isAlwaysTrue = true;
		else
		{
			minInclusive = (setting.charAt(0) == '[');
			maxInclusive = (setting.charAt(setting.length() - 1) == ']');
			String[] ss = StringUtils.splitIgnoreBlank(setting.substring(1,setting.length() - 1));
			if (ss.length != 2)
				throw new LoaderException("range should sperated by comma.");
			try
			{
				min = Integer.parseInt(ss[0]);
				if (min < 0)
					min = 0;
			}
			catch (Exception e)
			{
				throw new LoaderException("Invalid min value.");
			}
			try
			{
				if ('N' != ss[1].charAt(0))
				{
					max = Integer.parseInt(ss[1]);
					if (max < min)
						throw new LoaderException("Invalide range!");
				}
			}
			catch (Exception e)
			{
				throw new LoaderException("Invalid max value.");
			}
		}
	}

	public boolean isInRange(int v)
	{
		if (this.isAlwaysTrue)
			return true;
		if ((minInclusive && min > v) || (!minInclusive && min >= v)
				|| (max != -1 && ((maxInclusive && max < v) || (!maxInclusive && max <= v))))
		{
			return false;
		}
		return true;
	}

}
